﻿using System;
using CustomerContactSystem.Core.AppServices.Email;

namespace CustomerContactSystem.WebForms
{
    public partial class GetLogin : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack) {
                GetDepartments();
            }
        }

        private void GetDepartments() {
            var departments = DepartmentRepository.QueryOver().OrderBy(d => d.DepartmentName).Asc;
            BindDropDownList(DepartmentList, departments.List(), "DepartmentName", "Id", "--Select Department--", "0");
        }

        protected void DepartmentListSelectedIndexChanged(object sender, EventArgs e) {
            GetUsers();
        }

        private void GetUsers() {
            var departmentId = int.Parse(DepartmentList.SelectedItem.Value);
            var departmentUsers = UserRepository.QueryOver().Where(u => u.Department.Id == departmentId && u.IsActive);
            BindDropDownList(UserList, departmentUsers.List(), "DisplayName", "Id", "--Select Your Name--", "0");
        }

        protected void RetrieveLoginClick(object sender, EventArgs e)
        {
            var userId = int.Parse(UserList.SelectedItem.Value);
            var selectedUser = UserRepository.GetById(userId);

            if ((selectedUser != null))
            {
                var loginInfoEmail = new LoginDetailsEmail(ConfigSettings.AdminEmailAddress,
                                                       selectedUser.Email, selectedUser.Username,
                                                       selectedUser.Password);
                //var smtpService = new SmtpEmailService(ConfigSettings.GetStringSetting("SmptServerAddress"));
                EmailService.SendEmail(loginInfoEmail);
                RetrievalFormContent.Visible = false;
                ThankYouContent.Visible = true;
            }
            else
            {
                ErrorMsg.Text = "Your details could not be found. Please contact IT Support!";
            }
        }
    }
}